package batch

import (
	"time"

	"github.com/astaxie/beego/orm"

	"eccgateway/pkg/api/dataselect"
	"eccgateway/pkg/db/util"
)

type Batch struct {
	ID              string    `json:"id" orm:"column(id);unique;pk"`
	UserID          string    `json:"user_id" orm:"column(user_id)"`
	Username        string    `json:"username" orm:"column(username)"`
	Name            string    `json:"name" orm:"column(name)"`
	Type            string    `json:"type" orm:"column(type)"`
	CreateTimestamp time.Time `json:"create_timestamp" orm:"column(create_timestamp)"`
	StartTimestamp  time.Time `json:"start_timestamp" orm:"column(start_timestamp)"`
	EndTimestamp    time.Time `json:"end_timestamp" orm:"column(end_timestamp)"`
	Pending         string    `json:"pending" orm:"column(pending);type(text)"`
	Success         string    `json:"success" orm:"column(success);type(text)"`
	Failure         string    `json:"failure" orm:"column(failure);type(text)"`
	Status          string    `json:"status" orm:"column(status)"`
	Template        string    `json:"data" orm:"column(template);type(text)"`
}

var existKeyInBatch = map[string]bool{
	"id":               true,
	"user_id":          true,
	"username":         true,
	"name":             true,
	"type":             true,
	"create_timestamp": true,
	"start_timestamp":  true,
	"end_timestamp":    true,
	"pending":          true,
	"success":          true,
	"failure":          true,
	"status":           true,
	// not allow filter by template
	//"template":         true,
}

func (b *Batch) TableName() string {
	return "batch"
}

func (b *Batch) TableUnique() [][]string {
	return [][]string{
		{"id"},
		{"user_id", "name"},
	}
}

func (b *Batch) TableIndex() [][]string {
	return [][]string{
		{"user_id", "name"},
	}
}

func CreateBatch(o orm.Ormer, batch Batch) (Batch, error) {
	_, err := o.Insert(&batch)
	if err != nil {
		return batch, err
	}
	return GetBatchByNameAndUserID(o, batch.Name, batch.UserID)
}

func GetBatchByNameAndUserID(o orm.Ormer, name string, userID string) (Batch, error) {
	batch := Batch{}
	err := o.QueryTable(Batch{}).Filter("name", name).Filter("user_id", userID).One(&batch)
	return batch, err
}

func ListBatchByUserID(o orm.Ormer, userIDs []string, query *dataselect.DataSelectQuery) ([]Batch, int64, error) {
	batches := []Batch{}
	origin := o.QueryTable(Batch{})
	origin, count, err := util.Search(origin, userIDs, query, existKeyInBatch)
	if err != nil {
		return batches, 0, nil
	}
	_, err = origin.All(&batches)
	return batches, count, err
}

func ListAllBatch(o orm.Ormer) ([]Batch, error) {
	batches := []Batch{}
	_, err := o.QueryTable(Batch{}).All(&batches)
	return batches, err
}

func DeleteBatch(o orm.Ormer, batch Batch) error {
	_, err := o.Delete(&batch)
	return err
}

func UpdateBatch(o orm.Ormer, batch Batch) error {
	_, err := o.Update(&batch)
	return err
}
